<?php

namespace App\Http\Controllers;

use App\Models\Boxes;
use App\Models\User;
use App\Services\ShelveService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class HomeController extends Controller
{
    protected $request;

    /**
     * Create a new controller instance.
     * @return void
     */
    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    /**
     * 小程序登录
     * @return \Illuminate\Http\JsonResponse
     */
    public function login()
    {

        $url = 'https://api.weixin.qq.com/sns/jscode2session';
        $post = $this->request->post();

        //小程序登录需要参数
        $params = [
            'appid' => 'wxd3674930352a35ca',
            'secret' => '35431692fb275a29ad1309008d7c0e4b',
            'js_code' => $post['code'],
            'grant_type' => 'authorization_code',
        ];
        $response = Http::withOptions([
            'verify' => false,
        ])->get($url, $params);

        if ($response->ok()) {
            $loginInfo = $response->json();

            //判断用户是否存在
            $exist_user = User::where('openid', $loginInfo['openid'])->first();
            if ($exist_user){
                unset($exist_user->session_key);
                return Success('okk', $exist_user);
            }else{
                $insert = [
                    'openid' => $loginInfo['openid'],
                    'session_key' => $loginInfo['session_key'],
                    'avatar' => $post['avatar'],
                    'nickname' => $post['nickname'],
                    'create_time' => time()
                ];
                if (User::insert($insert)) {
                    unset($insert['session_key']);
                    return Success('ok', $insert);
                } else {
                    return Error('登录失败，请稍后重试！');
                }
            }

        } else {
            return Error('okk');
        }
    }

    /**
     * 扫码到货
     * @return \Illuminate\Http\JsonResponse
     */
    public function bind_arrive(){
        $post = $this->request->post();
        $tracking_no = trim($post['tracking_no']);

        $exist = Boxes::where('tracking_no',$tracking_no)->first();
        if ($exist){
            return Error('该货件已入仓，请勿重复操作！');
        }else{
            $box = [
                'tracking_no' => $tracking_no,
                'tracking_search' => substr($tracking_no, -6),
                'act_user_nickname' => $post['nickname'],
                'act_user_real_name' => isset($post['real_name'])?$post['real_name']:'',
                'act_user_openid' => $post['openid'],
                'in_time' => time(),
                'status' => 'in_warehouse'
            ];
            if (Boxes::insert($box)){
                return Success('ok', $post);
            }else{
                return Error('入仓失败，请稍后重试！');
            }
        }
    }

    /**
     * 扫码上架
     * @return \Illuminate\Http\JsonResponse
     */
    public function bind_shelve(ShelveService $shelveService){
        $post = $this->request->post();
        $tracking_no = trim($post['tracking_no']);
        $exist = Boxes::where('tracking_no',$tracking_no)->first();

        //处理货架信息
        $shelve = explode('-',$post['shelve_num']);
        $shelve_area = explode(' | ',$post['shelve_area']);

        //获取已上架数量
        $count = Boxes::where(['status' => 'on_shelve', 'shelve_no' => (int)$shelve[0], 'floor_num' => (int)$shelve[1]])->count();
        $on_sort = (int)$count + 1;
        $out_code = GenerateOutCode($post['shelve_num'], $on_sort);

        if ($exist){
            //生成取件码
            $update = [
                'on_sort' => $on_sort,
                'out_code' => $out_code,
                'shelve_no' => (int)$shelve[0],
                'floor_num' => (int)$shelve[1],
                'shelve_name' => $shelve_area[0],
                'area_num' => $shelve_area[1],
                'tracking_search' => substr($tracking_no, -6),
                'on_user_nickname' => $post['nickname'],
                'on_user_real_name' => isset($post['real_name'])?$post['real_name']:'',
                'on_user_openid' => $post['openid'],
                'on_time' => time(),
                'status' => 'on_shelve'
            ];
            if (Boxes::where('tracking_no', $tracking_no)->update($update)){
                return Success('ok', $exist);
            }else{
                return Error('入仓失败，请稍后重试！');
            }

        }else{  //新增
            $box = [
                'tracking_no' => $tracking_no,
                'on_sort' => $on_sort,
                'out_code' => $out_code,
                'shelve_no' => (int)$shelve[0],
                'floor_num' => (int)$shelve[1],
                'shelve_name' => $shelve_area[0],
                'area_num' => $shelve_area[1],
                'tracking_search' => substr($tracking_no, -6),
                'on_user_nickname' => $post['nickname'],
                'on_user_real_name' => isset($post['real_name'])?$post['real_name']:'',
                'on_user_openid' => $post['openid'],
                'on_time' => time(),
                'status' => 'on_shelve'
            ];
            if (Boxes::insert($box)){
                return Success('ok', $box);
            }else{
                return Error('入仓失败，请稍后重试！');
            }
        }
    }

    /**
     * 获取货架信息
     * @return \Illuminate\Http\JsonResponse
     */
    public function get_shelve(ShelveService $shelveService){
        $results = $shelveService->getShelveWithAreas();
        $shelve =  [];
        foreach ($results as $result){
            $areas = [];
            if (count($result->areas)){
                foreach ($result->areas as $area){
                    $areas[] = [
                        'text' => $area->area_name,
                        'value' => $area->shelve_no.'-'.$area->floor_num,
                    ];
                }

            }
            $shelve[] = [
                'text' => $result->shelve_name,
                'value' => $result->_id,
                'children' => $areas
            ];
        }

        return Success('ok', $shelve);
    }
}
